import React, { Component, Fragment } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { actionCreators } from '../store';

import { Button, Modal, Form, Input, Select, message } from 'antd';

const { Option } = Select;

class CreateConnection extends Component{
  state={
    visible: false,
    dataType: "",
    testCon: {},
  };

  handleClick = () => {
    this.setState({visible:true})
  };

  handleOk = (values) => {
    const {testCon} = this.state;
    let configName = values.configName;
    let description = values.description?values.description:"";
    let username ="admin";//待修改
    if(this.state.dataType==="MySQL"||this.state.dataType==="SQLServer"||this.state.dataType==="MongoDB"){
        let host = values.host;
        let port = values.port;
        let userName = values.userName;
        let password = values.password;
        let databaseName = values.databaseName;
        if(JSON.stringify(testCon)!=='{}'){
          if(testCon.host===host&&testCon.port===port&&testCon.userName===userName&&testCon.password===password){//如果修改了表单信息，进行测试连接的验证
            let params = {configName,description,host,port,userName,password,databaseName,username};
            this.props.saveCon(this.state.dataType,params,this.props.searchValue);
            this.formRef.current.resetFields();
            this.setState({visible:false,testCon:{}});
          }
          else{
            message.error("请先测试连接！");
          }
        }
        else{
          message.error("请先测试连接！");
        }
    }else if(this.state.dataType==="Oracle"){
        let host = values.host;
        let port = values.port;
        let userName = values.userName;
        let password = values.password;
        let database = values.database;
        if(JSON.stringify(testCon)!=='{}'){
          if(testCon.host===host&&testCon.port===port&&testCon.userName===userName&&testCon.password===password&&testCon.database===database){
            let params = {configName,description,host,port,userName,password,database,username};
            this.props.saveCon(this.state.dataType,params,this.props.searchValue);
            this.formRef.current.resetFields();
            this.setState({visible:false,testCon:{}});
          }
          else{
            message.error("请先测试连接！");
          }
        }
        else{
          message.error("请先测试连接！");
        }
    }else if(this.state.dataType==="HBase"){
        let master = values.master;
        let zookeeperQueue = values.zookeeperQueue;
        let zookeeperPort = values.zookeeperPort;
        if(JSON.stringify(testCon)!=='{}'){
          if(testCon.master===master&&testCon.zookeeperQueue===zookeeperQueue&&testCon.zookeeperPort===zookeeperPort){
            let params = {configName,description,master,zookeeperQueue,zookeeperPort,username};
            this.props.saveCon(this.state.dataType,params,this.props.searchValue);
            this.formRef.current.resetFields();
            this.setState({visible:false,testCon:{}});
          }
          else{
            message.error("请先测试连接！");
          }
        }
        else{
          message.error("请先测试连接！");
        }
    }
  };

  handleCancel = () => {
    this.setState({visible:false,dataType:""});
    this.formRef.current.resetFields();
  };

  chooseType = dataType => {
    this.setState({ dataType });
    this.props.cleanDatabase();
    if(this.state.dataType==="MySQL"||this.state.dataType==="SQLServer"||this.state.dataType==="MongoDB"){//修改数据类型时将表单置空
      this.formRef.current.setFieldsValue({host:undefined,port:undefined,userName:undefined,password:undefined,databaseName:undefined,description:undefined});
    }else if(this.state.dataType==="Oracle"){
      this.formRef.current.setFieldsValue({host:undefined,port:undefined,userName:undefined,password:undefined,database:undefined,description:undefined});
    }else if(this.state.dataType==="HBase"){
      this.formRef.current.setFieldsValue({master:undefined,zookeeperQueue:undefined,zookeeperPort:undefined,description:undefined});
    }
  };

  testCon = () => {
    if(this.state.dataType==="MySQL"||this.state.dataType==="SQLServer"||this.state.dataType==="MongoDB"){
      this.formRef.current.validateFields(["host","port","userName","password"])
      .then(values => {
        let host = values.host;
        let port = values.port;
        let userName = values.userName;
        let password = values.password;
        let params = {host,port,userName,password};
        this.setState({testCon: params});
        this.formRef.current.setFieldsValue({databaseName:undefined});
        this.props.testCon(this.state.dataType,params);
        //this.props.getAllDatabase(this.state.dataType,params);
      })
    }else if(this.state.dataType==="Oracle"){
      this.formRef.current.validateFields(["host","port","userName","password","database"])
      .then(values => {
        let host = values.host;
        let port = values.port;
        let userName = values.userName;
        let password = values.password;
        let database = values.database;
        let params = {host,port,userName,password,database};
        this.setState({testCon: params});
        this.props.testCon(this.state.dataType,params);
      })
    }else if(this.state.dataType==="HBase"){
      this.formRef.current.validateFields(["master","zookeeperQueue","zookeeperPort"])
      .then(values => {
        let master = values.master;
        let zookeeperQueue = values.zookeeperQueue;
        let zookeeperPort = values.zookeeperPort;
        let params = {master,zookeeperQueue,zookeeperPort};
        this.setState({testCon: params});
        this.props.testCon(this.state.dataType,params);
      })
    }
  };

  dataTypeForm = () => {
    if(this.state.dataType==="MySQL"||this.state.dataType==="SQLServer"||this.state.dataType==="MongoDB"){
      return(
      <Fragment>
        <Form.Item
          label="IP" name="host"
          rules={[
            {
              required: true,
              message: '请输入IP地址！',
            },]}>
          <Input placeholder="请输入IP地址"/>
        </Form.Item>
        <Form.Item
          label="端口号" name="port"
          rules={[
            {
              required: true,
              message: '请输入端口号！',
            },]}>
          <Input placeholder="请输入端口号"/>
        </Form.Item>
        <Form.Item
          label="用户名" name="userName"
          rules={[
            {
              required: true,
              message: '请输入用户名！',
            },]}>
          <Input placeholder="请输入用户名"/>
        </Form.Item>
        <Form.Item
          label="密码" name="password"
          rules={[
            {
              required: true,
              message: '请输入密码！',
            },]}>
          <Input.Password placeholder="请输入密码"/>
        </Form.Item>
        {/* <Form.Item
          label="归属部门" name="department"
          initialValue="公安"
          rules={[
            {
              required: true,
            },]}>
          <Input disabled/>
        </Form.Item> */}
        <Button type="primary" onClick={this.testCon} style={{marginBottom:24}}>测试连接</Button>
        <Form.Item
          label="选择数据库" name="databaseName"
          rules={[
            {
              required: true,
              message: "请选择数据库！"
            },]}>
          <Select placeholder="请选择数据库">
            {
              this.props.database.map(database=>(
                <Option value={database}>{database}</Option>
              ))
            }
          </Select>
        </Form.Item>
        <Form.Item label="备注" name="description">
          <Input.TextArea rows={4} placeholder="请输入内容"/>
        </Form.Item>
      </Fragment>
      )
    }else if(this.state.dataType==="Oracle"){
      return(
        <Fragment>
          <Form.Item
            label="IP" name="host"
            rules={[
              {
                required: true,
                message: '请输入IP地址！',
              },]}>
            <Input placeholder="请输入IP地址"/>
          </Form.Item>
          <Form.Item
            label="端口号" name="port"
            rules={[
              {
                required: true,
                message: '请输入端口号！',
              },]}>
            <Input placeholder="请输入端口号"/>
          </Form.Item>
          <Form.Item
            label="数据库名" name="database"
            rules={[
              {
                required: true,
                message: '请输入数据库名！',
              },]}>
            <Input placeholder="请输入数据库名"/>
          </Form.Item>
          <Form.Item
            label="用户名" name="userName"
            rules={[
              {
                required: true,
                message: '请输入用户名！',
              },]}>
            <Input placeholder="请输入用户名"/>
          </Form.Item>
          <Form.Item
            label="密码" name="password"
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },]}>
            <Input.Password placeholder="请输入密码"/>
          </Form.Item>
          {/* <Form.Item
            label="归属部门" name="department"
            initialValue="公安"
            rules={[
              {
                required: true,
              },]}>
            <Input disabled/>
          </Form.Item> */}
          <Button type="primary" onClick={this.testCon} style={{marginBottom:24}}>测试连接</Button>
          <Form.Item label="备注" name="description">
            <Input.TextArea rows={4} placeholder="请输入内容"/>
          </Form.Item>
        </Fragment>
      )
    }else if(this.state.dataType==="HBase"){
      return(
        <Fragment>
          <Form.Item
            label="HBase-Master地址" name="master"
            rules={[
              {
                required: true,
                message: '请输入HBase-Master地址！',
              },]}>
            <Input placeholder="请输入HBase-Master地址"/>
          </Form.Item>
          <Form.Item
            label="zookeeper队列" name="zookeeperQueue"
            rules={[
              {
                required: true,
                message: '请输入zookeeper队列！',
              },]}>
            <Input placeholder="请输入zookeeper队列"/>
          </Form.Item>
          <Form.Item
            label="zookeeper端口号" name="zookeeperPort "
            rules={[
              {
                required: true,
                message: '请输入zookeeper端口号！',
              },]}>
            <Input placeholder="请输入zookeeper端口号"/>
          </Form.Item>
          {/* <Form.Item
            label="归属部门" name="department"
            initialValue="公安"
            rules={[
              {
                required: true,
              },]}>
            <Input disabled/>
          </Form.Item> */}
          <Button type="primary" onClick={this.testCon} style={{marginBottom:24}}>测试连接</Button>
          <Form.Item label="备注" name="description">
            <Input.TextArea rows={4} placeholder="请输入内容"/>
          </Form.Item>
        </Fragment>
      )
    }
    return null;
  }

  componentDidMount(){
  };

  formRef = React.createRef();
  render(){
    return (
      <Fragment>
        <Button type="primary" style={{marginLeft: 24}} onClick={this.handleClick}>新建</Button>
        <Modal
          title="新建连接"
          visible={this.state.visible}
          //bodyStyle={{ padding: '12px 24px' }}
          onOk={() => {
            this.formRef.current
              .validateFields()
              .then(values => {
                this.handleOk(values);
              })
              .catch(info => {
                console.log('Validate Failed:', info);
              });
          }}
          onCancel={this.handleCancel}
          okText="确认"
          cancelText="取消"
        >
          <Form
            name="basic"
            ref={this.formRef}
          >
            <Form.Item
              label="数据源名称"
              name="configName"
              rules={[
                {
                  required: true,
                  message: '请输入数据源名称！',
                },]}>
              <Input placeholder="请输入数据源名称"/>
            </Form.Item>
            <Form.Item
              label="数据类型"
              name="dataType"
              rules={[
                {
                  required: true,
                  message: '选择数据类型！',
                },]}>
              <Select placeholder="选择数据类型" onChange={this.chooseType}>
                <Option value="MySQL">MySQL</Option>
                <Option value="SQLServer">SQLServer</Option>
                <Option value="Oracle">Oracle</Option>
                <Option value="HBase">HBase</Option>
                <Option value="MongoDB">MongoDB</Option>
              </Select>
            </Form.Item>
            { this.dataTypeForm() }
          </Form>
        </Modal>
      </Fragment>    
    );
  }
}

const mapStateToProps = (state) => {
  return {
    //dataSource: state.getIn(['Table','dataSource']),
    database: state.getIn(['connection','database']),
  }
}

const mapDispatchToProps = (dispatch) => ({
  getAllDatabase(dataType,params){
    dispatch(actionCreators.getAllDatabaseOperation(dataType,params));
  },
  cleanDatabase(){
    dispatch(actionCreators.cleanDatabaseOperation());
  },
  testCon(dataType,params){//测试连接
    dispatch(actionCreators.testConOperation(dataType,params));
  },
  saveCon(dataType,params,searchValue){
    dispatch(actionCreators.saveConOperation(dataType,params,searchValue));
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(CreateConnection);